package com.vn.egame.elazylite.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.electricwisdom.unifiedremotemetadataprovider.media.RemoteMetadataProvider;
import org.electricwisdom.unifiedremotemetadataprovider.media.enums.MediaCommand;
import org.electricwisdom.unifiedremotemetadataprovider.media.enums.PlayState;
import org.electricwisdom.unifiedremotemetadataprovider.media.enums.RemoteControlFeature;
import org.electricwisdom.unifiedremotemetadataprovider.media.listeners.OnArtworkChangeListener;
import org.electricwisdom.unifiedremotemetadataprovider.media.listeners.OnMetadataChangeListener;
import org.electricwisdom.unifiedremotemetadataprovider.media.listeners.OnPlaybackStateChangeListener;
import org.electricwisdom.unifiedremotemetadataprovider.media.listeners.OnRemoteControlFeaturesChangeListener;

import vn.egame.elockscreen.activity.LockApplication;
import vn.egame.elockscreen.service.AbstractRemoteControlService;
import vn.egame.elockscreen.service.RemoteControlService;
import vn.egame.elockscreen.service.RemoteControlServiceLollipop;
import android.annotation.TargetApi;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaMetadata;
import android.media.MediaMetadataRetriever;
import android.media.RemoteControlClient;
import android.media.RemoteController;
import android.media.session.MediaController;
import android.media.session.MediaSession;
import android.media.session.PlaybackState;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.egame.ewidget.utility.BrightnessUtility;
import com.egame.ewidget.utility.MobileDataUtility;
import com.egame.ewidget.utility.RingerModeUtitliy;
import com.egame.ewidget.utility.WiFiUtility;
import com.vn.egame.elazylite.R;
import com.vn.egame.elazylite.listener.FinishListener;
import com.vn.egame.elazylite.service.ListenerService;
import com.vn.egame.elazylite.utinities.AutoRotateUtility;
import com.vn.egame.elazylite.utinities.FlashTorchUtility;

import egame.launcher.dev.helper.SettingsHelper;
import egame.libs.android.util.DebugUtils;

@TargetApi(Build.VERSION_CODES.KITKAT)
public class UtinitiesFragment extends BaseFragment implements OnClickListener {

	private int[] stateUtilities = new int[2];

	private ImageView btnSetting, btnWifi, btnNetwork, btnBrightness, btnRing,
			btnFlash, btnLazySetting, btnCaculator, btnCamera, btnAutoRotate;

	// Control Music;
	private RemoteMetadataProvider mProvider;
	private RemoteController mRemoteController;
	RemoteController.OnClientUpdateListener controlMusicListener;
	boolean audioState;
	boolean isVisibleMusicView;
	private LinearLayout llControlMusic;
	private ImageView prevBut = null;
	private ImageView playBut = null;
	private ImageView nextBut = null;
	private TextView tvTitle, tvArtist;
	// private Slider sliderVolume;
	private AudioManager audio;
	int currentVolume;
	int maxVolume;
	private String playState;
	// > kitkat
	boolean isControlMusicOnKitKat = false;
	private AbstractRemoteControlService mRCService;
	protected boolean mBound = false;
	private LinearLayout llGuideMusic;
	private ImageView btnCloseGuide;
	private TextView msgGuide;
	private boolean mIsPlaying;
	private boolean isClickPlayPause;
	private boolean isPlaying;

	private FinishListener onFinishListener;

	public UtinitiesFragment(FinishListener finishListener) {
		onFinishListener = finishListener;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		// audioState = ((AudioManager) activity
		// .getSystemService(Context.AUDIO_SERVICE)).isMusicActive();

		audioState = true;

		if (!ListenerService.isRunning)
			activity.startService(new Intent(activity, ListenerService.class));

		if (audioState) {

			// Uri uri = Settings.System
			// .getUriFor(Settings.System.VOLUME_SETTINGS[AudioManager.STREAM_MUSIC]);

			// audio = (AudioManager) activity
			// .getSystemService(Context.AUDIO_SERVICE);
			//
			// currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
			// maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				// Acquiring instance of RemoteMetadataProvider
				DebugUtils.d("Kai", "control");

				mProvider = RemoteMetadataProvider.getInstance(activity);
				// setting up metadata listener
				mProvider
						.setOnMetadataChangeListener(new OnMetadataChangeListener() {
							@Override
							public void onMetadataChanged(String artist,
									String title, String album,
									String albumArtist, long duration) {

								DebugUtils.d("Kai", artist + " " + title);
								try {
									// if (!isVisibleMusicView) {
									// isVisibleMusicView = true;
									// // audioState = ((AudioManager) activity
									// //
									// .getSystemService(Context.AUDIO_SERVICE))
									// // .isMusicActive();
									// if (audioState) {
									//
									// llControlMusic
									// .setVisibility(View.VISIBLE);
									//
									// } else {
									//
									// llControlMusic
									// .setVisibility(View.GONE);
									//
									// }
									//
									// }

									if (artist != null && artist.length() > 1) {
										tvArtist.setText(artist);
										// tvArtist.setVisibility(View.VISIBLE);
									} else {
										tvArtist.setText(getString(R.string.unknown));
										// tvArtist.setVisibility(View.GONE);
									}

									if (title != null && title.length() > 1) {
										tvTitle.setText(title);
										// tvTitle.setVisibility(View.VISIBLE);
									} else {
										tvArtist.setText(getString(R.string.unknown));
										// tvTitle.setVisibility(View.GONE);
									}
								} catch (Exception ex) {
								}

							}
						});

				// setting up artwork listener
				mProvider
						.setOnArtworkChangeListener(new OnArtworkChangeListener() {
							@Override
							public void onArtworkChanged(Bitmap artwork) {
								// mArtwork.setImageBitmap(artwork);
							}
						});

				// setting up remote control flags listener
				mProvider
						.setOnRemoteControlFeaturesChangeListener(new OnRemoteControlFeaturesChangeListener() {
							@Override
							public void onFeaturesChanged(
									List<RemoteControlFeature> usesFeatures) {

							}
						});

				// setting up playback state change listener
				mProvider
						.setOnPlaybackStateChangeListener(new OnPlaybackStateChangeListener() {
							@Override
							public void onPlaybackStateChanged(
									PlayState playbackState) {
								// mStateTextView.setText("PLAYBACK STATE: "
								// + playbackState.name());

								try {
									playState = playbackState.name();

									if (playbackState.name().equals("PLAYING")) {
										playBut.setImageResource(R.drawable.btn_pause_player);
										isPlaying = true;
									} else {
										playBut.setImageResource(R.drawable.btn_play_player);

										isPlaying = false;
									}

								} catch (Exception ex) {
								}

							}
						});

			} else {

				isControlMusicOnKitKat = true;
			}

		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		rootView = inflater
				.inflate(R.layout.utinities_layout, container, false);
		return rootView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);
		init();
	}

	private void init() {
		btnSetting = (ImageView) rootView.findViewById(R.id.btn_setting);
		btnWifi = (ImageView) rootView.findViewById(R.id.btn_wifi);
		btnNetwork = (ImageView) rootView.findViewById(R.id.btn_mobile_data);
		btnBrightness = (ImageView) rootView.findViewById(R.id.btn_brightness);
		btnRing = (ImageView) rootView.findViewById(R.id.btn_ringer);
		btnFlash = (ImageView) rootView.findViewById(R.id.btn_flash);
		btnLazySetting = (ImageView) rootView
				.findViewById(R.id.btn_lazy_setting);
		btnCaculator = (ImageView) rootView.findViewById(R.id.btn_caculator);
		btnCamera = (ImageView) rootView.findViewById(R.id.btn_camera);
		btnAutoRotate = (ImageView) rootView.findViewById(R.id.btn_lock);

		tvTitle = (TextView) rootView.findViewById(R.id.tv_title_music);
		tvTitle.setSelected(true);
		tvArtist = (TextView) rootView.findViewById(R.id.tv_aritist_music);
		tvArtist.setSelected(true);
		// tvTitle.setVisibility(View.GONE);
		prevBut = (ImageView) rootView.findViewById(R.id.btn_lazy_pre);
		// setOnTouchButton(prevBut);
		playBut = (ImageView) rootView.findViewById(R.id.btn_lazy_play_pause);

		nextBut = (ImageView) rootView.findViewById(R.id.btn_lazy_next);

		llControlMusic = (LinearLayout) rootView
				.findViewById(R.id.llControlMusic);

		btnSetting.setOnClickListener(this);
		btnWifi.setOnClickListener(this);
		btnNetwork.setOnClickListener(this);
		btnBrightness.setOnClickListener(this);
		btnRing.setOnClickListener(this);
		btnFlash.setOnClickListener(this);
		btnLazySetting.setOnClickListener(this);
		btnCaculator.setOnClickListener(this);
		btnCamera.setOnClickListener(this);
		btnAutoRotate.setOnClickListener(this);
		prevBut.setOnClickListener(this);
		playBut.setOnClickListener(this);
		nextBut.setOnClickListener(this);

		stateUtilities[0] = WiFiUtility.isEnabled(mContext) == true ? 1 : 0;
		if (stateUtilities[0] == 1)
			btnWifi.setSelected(true);
		else
			btnWifi.setSelected(false);

		stateUtilities[1] = MobileDataUtility.isEnableNew(mContext) == true ? 1
				: 0;
		if (stateUtilities[1] == 1)
			btnNetwork.setSelected(true);
		else
			btnNetwork.setSelected(false);

		int brightnessMode = BrightnessUtility.getBrightnessMode(mContext);
		switch (brightnessMode) {
		case BrightnessUtility.BRIGHTNESS_LOW:

			btnBrightness.setImageResource(R.drawable.ic_brightness_low);

			break;

		case BrightnessUtility.BRIGHTNESS_MEDIUM:
			btnBrightness
					.setImageResource(R.drawable.ic_brightness_medium_click);

			break;
		case BrightnessUtility.BRIGHTNESS_HIGH:
			btnBrightness
					.setImageResource(R.drawable.ic_brightness_hight_click);

			break;
		case BrightnessUtility.BRIGHTNESS_AUTO:
			btnBrightness.setImageResource(R.drawable.ic_brightness_auto_click);

			break;
		}

		int ringMode = RingerModeUtitliy.getRingerMode(mContext);

		switch (ringMode) {
		case RingerModeUtitliy.RING_MODE_NORMAL:
			btnRing.setImageResource(R.drawable.ic_sound_click);
			break;

		case RingerModeUtitliy.RING_MODE_SILENT:
			btnRing.setImageResource(R.drawable.ic_vibrate_click);
			break;
		case RingerModeUtitliy.RING_MODE_VIBRATE:
			btnRing.setImageResource(R.drawable.ic_sound);
			break;
		}
		btnRing.setSelected(true);

		if (FlashTorchUtility.isFlashLightEnabled(mContext))
			btnFlash.setSelected(true);
		else
			btnFlash.setSelected(false);

		if (AutoRotateUtility.isAutoRotateEnabled(mContext)) {
			btnAutoRotate.setSelected(true);
		} else
			btnAutoRotate.setSelected(false);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if (v == btnSetting) {
			startActivity(new Intent(Settings.ACTION_SETTINGS));
			onFinishListener.onFinishListener();

		} else if (v == btnWifi) {
			if (stateUtilities[0] == 1) {

				stateUtilities[0] = 0;
				WiFiUtility.setEnabled(mContext, false);
				btnWifi.setSelected(false);
			} else {
				stateUtilities[0] = 1;
				WiFiUtility.setEnabled(mContext, true);
				btnWifi.setSelected(true);
			}
		} else if (v == btnNetwork) {
			// Toast.makeText(mContext, "clock", 1000).show();

			if (stateUtilities[1] == 1) {
				stateUtilities[1] = 0;
				MobileDataUtility.setEnabled(mContext, false);
				btnNetwork.setSelected(false);
			} else {
				stateUtilities[1] = 1;
				MobileDataUtility.setEnabled(mContext, true);
				btnNetwork.setSelected(true);
			}
		} else if (v == btnBrightness) {
			int brightnessMode = BrightnessUtility.nextMode(BrightnessUtility
					.getBrightnessMode(mContext));

			BrightnessUtility.setBrightnessMode(mContext, brightnessMode);
			switch (brightnessMode) {
			case BrightnessUtility.BRIGHTNESS_LOW:

				btnBrightness.setImageResource(R.drawable.ic_brightness_low);

				break;

			case BrightnessUtility.BRIGHTNESS_MEDIUM:
				btnBrightness
						.setImageResource(R.drawable.ic_brightness_medium_click);

				break;
			case BrightnessUtility.BRIGHTNESS_HIGH:
				btnBrightness
						.setImageResource(R.drawable.ic_brightness_hight_click);

				break;
			case BrightnessUtility.BRIGHTNESS_AUTO:
				btnBrightness
						.setImageResource(R.drawable.ic_brightness_auto_click);

				break;
			}
		} else if (v == btnRing) {
			int ringMode = RingerModeUtitliy.nextMode(RingerModeUtitliy
					.getRingerMode(mContext));
			RingerModeUtitliy.setRingerMode(mContext, ringMode);
			switch (ringMode) {
			case RingerModeUtitliy.RING_MODE_NORMAL:
				btnRing.setImageResource(R.drawable.ic_sound_click);
				break;

			case RingerModeUtitliy.RING_MODE_SILENT:
				btnRing.setImageResource(R.drawable.ic_vibrate_click);
				break;
			case RingerModeUtitliy.RING_MODE_VIBRATE:
				btnRing.setImageResource(R.drawable.ic_sound);
				break;
			}
		} else if (v == btnFlash) {

			if (!FlashTorchUtility.isFlashLightAccessible(mContext)) {
				Toast.makeText(mContext, "Flash not suport", Toast.LENGTH_LONG)
						.show();
				return;
			}
			if (FlashTorchUtility.isFlashLightEnabled(mContext)) {
				mContext.sendBroadcast(new Intent(
						ListenerService.ACTION_TURNOFF_FLASH));
				btnFlash.setSelected(false);
			} else {
				mContext.sendBroadcast(new Intent(
						ListenerService.ACTION_TURNON_FLASH));
				btnFlash.setSelected(true);
			}
		} else if (v == btnLazySetting) {

		} else if (v == btnCaculator) {
			ArrayList<HashMap<String, Object>> items = new ArrayList<HashMap<String, Object>>();
			PackageManager pm;
			pm = activity.getPackageManager();
			List<PackageInfo> packs = pm.getInstalledPackages(0);
			for (PackageInfo pi : packs) {
				if (pi.packageName.toString().toLowerCase().contains("calcul")) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("appName", pi.applicationInfo.loadLabel(pm));
					map.put("packageName", pi.packageName);
					items.add(map);
				}
			}

			if (items.size() >= 1) {
				String packageName = (String) items.get(0).get("packageName");
				Intent i = pm.getLaunchIntentForPackage(packageName);
				if (i != null)
					startActivity(i);
			}

			onFinishListener.onFinishListener();
		} else if (v == btnCamera) {
			Intent intent = new Intent(
					MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
			startActivity(intent);

			onFinishListener.onFinishListener();
		} else if (v == btnAutoRotate) {
			if (AutoRotateUtility.isAutoRotateEnabled(mContext)) {
				btnAutoRotate.setSelected(false);
				AutoRotateUtility.setAutoRotateEnabled(mContext, false);
			} else {
				btnAutoRotate.setSelected(true);
				AutoRotateUtility.setAutoRotateEnabled(mContext, true);
			}
		} else if (v == prevBut) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				if (!mProvider.sendMediaCommand(MediaCommand.PREVIOUS)) {
					playBut.setImageResource(R.drawable.btn_play_player);
					// llControlMusic.setVisibility(View.GONE);
				}
			} else {

				if (mBound) {
					mRCService.sendPreviousKey();
				}

			}
		} else if (v == playBut) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {

				if (!isClickPlayPause) {
					isClickPlayPause = true;
					if (isPlaying) {
						playBut.setImageResource(R.drawable.btn_play_player);
						// isPlaying = true;
					} else {
						playBut.setImageResource(R.drawable.btn_pause_player);
					}
					if (!mProvider.sendMediaCommand(MediaCommand.PLAY_PAUSE)) {
						playBut.setImageResource(R.drawable.btn_play_player);
						// llControlMusic.setVisibility(View.GONE);
					}
					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							isClickPlayPause = false;
						}
					}, 1000);
				}
			} else {
				if (!isClickPlayPause) {
					isClickPlayPause = true;
					if (mBound) {
						if (mIsPlaying) {
							mRCService.sendPauseKey();
							mIsPlaying = false;
							playBut.setImageResource(R.drawable.btn_play_player);

						} else {
							mIsPlaying = true;
							mRCService.sendPlayKey();
							playBut.setImageResource(R.drawable.btn_pause_player);
						}
					}

					new Handler().postDelayed(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							isClickPlayPause = false;
						}
					}, 1000);
				}
			}
		} else if (v == nextBut) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				if (!mProvider.sendMediaCommand(MediaCommand.NEXT)) {
					playBut.setImageResource(R.drawable.btn_play_player);
					// llControlMusic.setVisibility(View.GONE);
				}
			} else {
				if (mBound) {
					mRCService.sendNextKey();
				}
			}

		}
	}

	@TargetApi(Build.VERSION_CODES.KITKAT)
	@Override
	public void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		if (isControlMusicOnKitKat && audioState) {

			controlMusicListener = new RemoteController.OnClientUpdateListener() {
				@Override
				public void onClientChange(boolean clearing) {
					if (clearing) {
						// template.setBackgroundColor(Color.WHITE, false);
						try {
							tvArtist.setText(R.string.unknown);
							tvTitle.setText(R.string.unknown);
						} catch (Exception ex) {
						}
					}
				}

				@Override
				public void onClientPlaybackStateUpdate(int state) {
					try {
						switch (state) {
						case RemoteControlClient.PLAYSTATE_PLAYING:
							mIsPlaying = true;
							playBut.setImageResource(R.drawable.btn_pause_player);
							break;
						default:
							mIsPlaying = false;
							playBut.setImageResource(R.drawable.btn_play_player);
							break;
						}
					} catch (Exception ex) {
					}
				}

				@Override
				public void onClientPlaybackStateUpdate(int state,
						long stateChangeTimeMs, long currentPosMs, float speed) {
					// progressBar.setProgress((int) TimeUnit.MILLISECONDS
					// .toSeconds(currentPosMs));
					try {
						switch (state) {
						case RemoteControlClient.PLAYSTATE_PLAYING:
							mIsPlaying = true;
							playBut.setImageResource(R.drawable.btn_pause_player);
							break;
						default:
							mIsPlaying = false;
							playBut.setImageResource(R.drawable.btn_play_player);
							break;
						}
					} catch (Exception ex) {
					}
				}

				@Override
				public void onClientTransportControlUpdate(
						int transportControlFlags) {
				}

				@Override
				public void onClientMetadataUpdate(
						RemoteController.MetadataEditor metadataEditor) {
					// some players write artist name to
					// METADATA_KEY_ALBUMARTIST
					// instead of METADATA_KEY_ARTIST, so we should double-check
					// it

					try {

						String artist = metadataEditor
								.getString(
										MediaMetadataRetriever.METADATA_KEY_ARTIST,
										metadataEditor
												.getString(
														MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST,
														getString(R.string.unknown)));
						String title = metadataEditor.getString(
								MediaMetadataRetriever.METADATA_KEY_TITLE,
								getString(R.string.unknown));
						songDuration = metadataEditor
								.getLong(
										MediaMetadataRetriever.METADATA_KEY_DURATION,
										1);
						tvArtist.setText(artist);
						tvTitle.setText(title);
						// Bitmap bitmap = metadataEditor.getBitmap(
						// RemoteController.MetadataEditor.BITMAP_KEY_ARTWORK,
						// null);

						// audioState = ((AudioManager) activity
						// .getSystemService(Context.AUDIO_SERVICE))
						// .isMusicActive();
						// if (audioState && title.length() > 1
						// && artist.length() > 1) {
						//
						// llControlMusic.setVisibility(View.VISIBLE);
						// isVisibleMusicView = true;
						// } else {
						//
						// // llControlMusic.setVisibility(View.GONE);
						// // isVisibleMusicView = false;
						// }
					} catch (Exception ex) {
					}

					// if (bitmap != null) {
					// // template.setBackgroundDrawable(new BitmapDrawable(
					// // getResources(), bitmap), false);
					// } else {
					// // template.setBackgroundColor(Color.WHITE, false);
					// }
				}
			};

			Intent intent;
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
				DebugUtils.d("Kai", "Kai  vao day kitkat");
				intent = LockApplication.createExplicitFromImplicitIntent(
						activity, new Intent(
								RemoteControlService.BIND_SERVICE_KITKAT));
			} else
				intent = LockApplication
						.createExplicitFromImplicitIntent(
								activity,
								new Intent(
										RemoteControlServiceLollipop.BIND_SERVICE_LOLIPOP));
			try {
				activity.bindService(intent, serviceConnection,
						Context.BIND_AUTO_CREATE);
			} catch (RuntimeException e) {
				DebugUtils.d("Kai", "Kai loi roi");
				e.printStackTrace();
				// showUnregistered();
			}

		}
	}

	private ServiceConnection serviceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			// Getting the binder and activating RemoteController instantly
			AbstractRemoteControlService.RCBinder binder = (AbstractRemoteControlService.RCBinder) service;
			mRCService = binder.getService();

			mRCService.setRemoteControllerEnabled();

			DebugUtils.d("Kai", "Kai " + mRCService.isConnect);

			if (mRCService.isConnect) {
				llGuideMusic.setVisibility(View.GONE);
				// llControlMusic.setVisibility(View.VISIBLE);

				// Not registered on the settings

				if (mRCService instanceof RemoteControlService)
					((RemoteControlService) mRCService)
							.setClientUpdateListener(controlMusicListener);
				else
					((RemoteControlServiceLollipop) mRCService)
							.setClientUpdateListener(new RemoteControlServiceLollipop.MediaControllerListener() {
								@Override
								public void onSessionDestroyed() {
									controlMusicListener.onClientChange(true);
								}

								@Override
								public void onSessionEvent(
										@NonNull String event,
										@Nullable Bundle extras) {
								}

								@TargetApi(Build.VERSION_CODES.LOLLIPOP)
								@Override
								public void onPlaybackStateChanged(
										@NonNull PlaybackState state) {

									// Log.d("Kai",
									// "Kai play back change "
									// + state.getState());

									try {
										switch (state.getState()) {
										case RemoteControlClient.PLAYSTATE_PLAYING:
											mIsPlaying = true;
											playBut.setImageResource(R.drawable.btn_pause_player);

											// if (getAudioSound(mContext)) {
											// mPlayPauseButton
											// .setImageResource(android.R.drawable.ic_media_pause);
											// mIsPlaying = true;
											// } else {
											// mPlayPauseButton
											// .setImageResource(android.R.drawable.ic_media_play);
											// mIsPlaying = false;
											// }
											break;
										default:
											mIsPlaying = false;

											playBut.setImageResource(R.drawable.btn_play_player);
											// if (getAudioSound(mContext)) {
											// mPlayPauseButton
											// .setImageResource(android.R.drawable.ic_media_pause);
											// mIsPlaying = true;
											// } else {
											// mPlayPauseButton
											// .setImageResource(android.R.drawable.ic_media_play);
											// mIsPlaying = false;
											// }
											break;
										}
									} catch (Exception ex) {
									}
									// listener.onClientPlaybackStateUpdate(state
									// .getState() ==
									// PlaybackState.STATE_PLAYING ?
									// RemoteControlClient.PLAYSTATE_PLAYING
									// : -1);
								}

								@TargetApi(Build.VERSION_CODES.LOLLIPOP)
								@Override
								public void onMetadataChanged(
										@Nullable MediaMetadata metadata) {

									// Log.d("Kai", "Kai metadata change ");

									try {
										if (metadata != null) {

											// if (!isVisibleMusicView) {
											// isVisibleMusicView = true;
											// audioState = ((AudioManager)
											// activity
											// .getSystemService(Context.AUDIO_SERVICE))
											// .isMusicActive();
											// if (audioState) {
											//
											// llControlMusic
											// .setVisibility(View.VISIBLE);
											// } else {
											//
											// llControlMusic
											// .setVisibility(View.GONE);
											//
											// }
											//
											// }

											String artist = metadata
													.getString(MediaMetadata.METADATA_KEY_ARTIST);
											if (artist == null)
												artist = metadata
														.getString(MediaMetadata.METADATA_KEY_ALBUM_ARTIST);
											if (artist == null)
												artist = getString(R.string.unknown);
											String title = metadata
													.getString(MediaMetadata.METADATA_KEY_TITLE);

											long songDuration = metadata
													.getLong(MediaMetadata.METADATA_KEY_DURATION);
											tvArtist.setText(artist);
											tvTitle.setText(title);
											Bitmap bitmap = metadata
													.getBitmap(MediaMetadata.METADATA_KEY_ART);
											if (bitmap == null)
												bitmap = metadata
														.getBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART);
											if (bitmap != null) {

											} else {

											}
										} else {
											tvArtist.setText(R.string.unknown);
											tvTitle.setText(R.string.unknown);

										}
									} catch (Exception ex) {
									}
								}

								@Override
								public void onQueueChanged(
										@Nullable List<MediaSession.QueueItem> queue) {
								}

								@Override
								public void onQueueTitleChanged(
										@Nullable CharSequence title) {
								}

								@Override
								public void onExtrasChanged(
										@Nullable Bundle extras) {
								}

								@Override
								public void onAudioInfoChanged(
										MediaController.PlaybackInfo info) {
								}
							});

			} else {

				if (!"samsung".equals(Build.MANUFACTURER)) {
					llGuideMusic.setVisibility(View.VISIBLE);
				}

				if ("samsung".equals(Build.MANUFACTURER)
						&& SettingsHelper.isGuideMusicOnSamsung(mContext)) {
					llGuideMusic.setVisibility(View.VISIBLE);
					SettingsHelper.setGuideMusicOnSamsung(mContext, false);
				}
			}

			mBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mBound = false;
		}
	};

	protected long songDuration;

	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (isControlMusicOnKitKat && audioState) {
			if (mBound) {
				mRCService.setRemoteControllerDisabled();
			}
			activity.unbindService(serviceConnection);
		}
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		if (audioState) {
			// if (mRemoteMetadataProvider != null) {
			// mRemoteMetadataProvider.acquireRemoteControls();
			// }

			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR2) {
				mProvider.acquireRemoteControls();
			} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				mProvider.acquireRemoteControls(300, 300);
			} else {

			}
		}

	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

		if (audioState) {
			if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
				// dropping remote media controls
				mProvider.dropRemoteControls(true);
			}
		}
	}

	public FinishListener getOnFinishListener() {
		return onFinishListener;
	}

	public void setOnFinishListener(FinishListener onFinishListener) {
		this.onFinishListener = onFinishListener;
	}

}
